package org.ricks.log;

import org.ricks.log.message.Message;
import org.ricks.log.message.MessageFactory;

/**
 * @author chenwei
 * @Description: 日志入口
 * @date 2023/1/915:59
 */
public class RicksLogger {

    private static final AsyncLoggerDisruptor asyncLoggerDisruptor = LogManager.getAsyncLoggerDisruptor();

    public static boolean isDebugEnabled() {
        return isEnabled(Level.DEBUG);
    }

    public static void debug(String msg) {
        logIfEnabled(Level.DEBUG, msg);
    }

    public static void debug(String msg, Object... args) {
        logIfEnabled(Level.DEBUG, msg, args);
    }

    public static boolean isInfoEnabled() {
        return isEnabled(Level.INFO);
    }

    public static void info(String msg) {
        logIfEnabled(Level.INFO, msg);
    }

    public static void info(String msg, Object... args) {
        logIfEnabled(Level.INFO, msg, args);
    }

    public static boolean isWarnEnabled() {
        return isEnabled(Level.WARN);
    }

    public static void warn(String msg) {
        logIfEnabled(Level.WARN, msg);
    }

    public static void warn(String msg, Object... args) {
        logIfEnabled(Level.WARN, msg, args);
    }

    public static boolean isErrorEnabled() {
        return isEnabled(Level.ERROR);
    }

    public static void error(String msg) {
        logIfEnabled(Level.ERROR, msg);
    }

    public static void error(String msg, Object... args) {
        logIfEnabled(Level.ERROR, msg, args);
    }

    /**
     * 判定日志级别是否达标
     *
     * @param level 日志级别
     * @return 如果达标则返回true
     */
    private static boolean isEnabled(Level level) {
        return LogConfig.getLevel() <= level.getValue();
    }

    /**
     * 记录日志，如果级别达标的话.
     *
     * @param level 日志级别
     * @param msg   日志文本
     * @param args  日志参数
     */
    private static void logIfEnabled(Level level, String msg, Object... args) {
        if (isEnabled(level)) {
            logMessage(level, msg, args);
        }
    }

    /**
     * 记录日志.
     *
     * @param level 日志等级
     * @param msg   日志信息
     * @param args  日志参数
     */
    private static void logMessage(Level level, String msg, Object... args) {
        Message message = MessageFactory.create(msg, args);
        asyncLoggerDisruptor.publish(new AsyncLogEvent(level, message));
    }
}
